package com.by.service.impl;

import com.by.common.core.utils.Assert;
import com.by.entity.Order;
import com.by.entity.OrderItem;
import com.by.mapper.OrderAddrMapper;
import com.by.mapper.OrderItemMapper;
import com.by.mapper.OrderMapper;
import com.by.service.OrderService;
import com.by.utils.OrderNum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.List;
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderAddrMapper orderAddrMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderNum orderNum;

    //生成订单
    @Transactional
    @Override
    public boolean saveOrder(Order order) {
        //sql执行结果
        int rs = 0;
        //订单总金额
        BigDecimal totalAmount = BigDecimal.valueOf(0);

        //1.尝试锁定库存  如果锁定成功，就生成订单 锁定失败就提示锁定库存失败，订单无法生成
        //锁定失败就提示锁定库存失败，订单无法生成
        if(false) {
            Assert.isZero(rs, "锁定库存失败，订单无法生成");
        }



        //2.如果锁定成功，保存收货地址
        String orderAddr = orderAddrMapper.selectAddrByOrderAddrId(order.getOrderAddrId());
        if(null!=orderAddr){
        }

        Integer orderAddrId=orderAddrMapper.selectIdByAdds(order.getAddr(), order.getUserId());
        if(null!=orderAddrId){
            //如果不存在则保存地址并返回地址id
            //rs = orderAddrMapper.insert(order.getAddr()); 保存地址
            orderAddrId=orderAddrMapper.selectIdByAdds(order.getAddr(),order.getUserId());
        }

        //3.生成订单

        //3.1生成订单编号
        String orderNo = orderNum.generateOrderNo();
        order.setOrderNo(orderNo);
        //记录地址id
        order.setOrderAddrId(orderAddrId);

        //3.2计算订单总金额
        List<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            BigDecimal spuTotalAmount= (orderItem.getPrice()).multiply(new BigDecimal(orderItem.getCount()));
            orderItem.setSpuTotalAmount(spuTotalAmount);
            totalAmount = totalAmount.add(spuTotalAmount);
        }
        order.setTotal(totalAmount);


        //3.2保存订单基本信息
        rs = orderMapper.insert(order);
        Assert.isZero(rs, "保存订单基本信息失败");
        //3.3保存订单项
        Iterator<OrderItem> it = order.getOrderItems().iterator();
        while (it.hasNext()) {
            OrderItem item = it.next();
            item.setOrderId(order.getOrderId());
            rs = orderItemMapper.insert(item);
            Assert.isZero(rs, "保存订单项失败");
        }

        return true;
    }
}
